package org.batatasframework.web.method.resolver;

import javax.servlet.http.HttpServletRequest;

import org.batatasframework.common.ParameterReader;
import org.batatasframework.web.RequestParameterReader;
import org.batatasframework.web.annotations.EventSource;
import org.batatasframework.web.event.AccessEvent;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.ModelAndViewContainer;

import cn.bonoon.kernel.security.LogonUser;


public class EventArgumentResolver extends AbstractArgumentResolver{

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		Class<?> paramType = parameter.getParameterType();
		return ParameterReader.class.isAssignableFrom(paramType) || 
				AccessEvent.class.isAssignableFrom(paramType);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter,
			ModelAndViewContainer mavContainer, NativeWebRequest webRequest,
			WebDataBinderFactory binderFactory) throws Exception {
		
		Class<?> paramType = parameter.getParameterType();
		HttpServletRequest nativeRequest = webRequest.getNativeRequest(HttpServletRequest.class);
		
		if(ParameterReader.class.isAssignableFrom(paramType)){
			return new RequestParameterReader(nativeRequest);
		}
		
		LogonUser user = getUser();
		if(AccessEvent.class.isAssignableFrom(paramType)){
			EventSource source = parameter.getParameterAnnotation(EventSource.class);
			Object sourceObject = null;
			if(null != source){
				
			}
			return new AccessEvent(user, nativeRequest, sourceObject);
		}

		return unsupported(parameter);
	}

}
